import axios from "axios";
import apiconfig from "@/api/apiConfig";
import router from '@/view/teamActivity/router/route.js'
import store from '@/store/index'
import Vue from 'vue'
import qs from 'qs'
import { getClientIp, jwtToken } from "./common";
// import mockData from "./mockData"
const codeArray = [-1, 5004, 5005]; //登陆失效返回的code码
function getCookie(name) {
  var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
  arr = document.cookie.match(reg)
  if (arr) {
    return unescape(arr[2]);
  } else {
    return null;
  }
}
let requests = [];
let isRefreshing = false;
const commonAxios = axios.create();
commonAxios.defaults.headers.post["Content-Type"] = "application/json;charset=UTF-8";
// commonAxios.defaults.withCredentials = true;
// commonAxios.defaults.timeout = 5000;   
const payAxios = (option) => {
  commonAxios.defaults.baseURL = apiconfig['API'][option.baseUrl];
  commonAxios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
  if (option.contentType) {
    commonAxios.defaults.headers.common['content-Type'] = option.contentType;
  }
  return commonAxios;
};

let hostLocal = apiconfig.YX_WEB;
let ssoapihost = apiconfig.SSO_API_HOST;
export const getKeyHref = function (key) {
  let href = window.location.href;
  let arraykey = [];
  if (href.indexOf("?") > -1) {
    arraykey = href.split("?")[1].split("&");
  } else {
    return;
  }
  let obj = {};
  for (let i = 0; i < arraykey.length; i++) {
    let item = arraykey[i].split("=");
    obj[item[0].toUpperCase()] = item[1];
  }
  return obj[key]
}
export const isLogin = async function () {
  let returnUrl = ''
  if (window.location.href.indexOf("teamActivity")) {
    returnUrl = apiconfig['returnURLTeam'] + router.currentRoute.params.activityCode;
  } else {
    returnUrl = apiconfig['returnURL'];
  }
  let newHref = apiconfig["YX_WEB"] + '/search/common/login?returnUrl=' + returnUrl + '?appId=' + apiconfig['appid'];
  window.location.href = newHref;
}

async function refreshToken() {

  // instance是当前request.js中已创建的axios实例
  if (!store.state.clientIp) {
    await getClientIp().then(res => {
      store.state.clientIp = res.Data;
      store.commit("getClientIpState", res.Data)
    })
  }
  let obj = {};
  if (window.location.href.indexOf("192") > -1) {
    obj = {
      EcpToken: apiconfig['DEV_Token'],
      ClientIp: '124.193.98.145',
      AppId: apiconfig['appid'],
      // ClientId: Vue.$cookies.get("Ecp_ClientId")
      ClientId: '3220308055500668883'
    };
  } else {
    obj = {
      EcpToken: getCookie(apiconfig['enveriment']),
      ClientIp: store.state.clientIp,
      AppId: apiconfig['appid'],
      ClientId: Vue.$cookies.get("Ecp_ClientId")
    };
  }
  commonAxios.defaults.baseURL = '/api'
  return jwtToken(obj).then(res => res.Content);
}
// 给实例添加一个setToken方法，用于登录后方便将最新token动态添加到header，同时将token保存在localStorage中
commonAxios.setToken = (obj) => {
  commonAxios.defaults.headers['Authorization'] = `Bearer ` + obj.JwtToken
  // if(window.localStorage.getItem('token')["JwtToken"]){
  //   window.localStorage.removeItem('token')
  // }else{
  window.localStorage.setItem('token', JSON.stringify(obj)) // 注意这里需要变成字符串后才能放到localStorage中
  // }
}
commonAxios.interceptors.request.use((config) => {
  // debugger
  let tokenObj = {};
  let obj = localStorage.getItem('token')
  tokenObj = obj ? JSON.parse(obj) : {}
  // 添加请求头
  if (tokenObj.JwtToken) {
    config.headers['Authorization'] = `Bearer ` + tokenObj.JwtToken
  }
  // 登录接口和刷新token接口绕过
  if (config.url.indexOf('/ecptoken') >= 0 || config.url.indexOf('/login') >= 0) {
    return config
  }
  if (tokenObj.JwtToken && tokenObj.ExpireIn || (!tokenObj.JwtToken)) {
    const now = Date.now()
    if (now >= tokenObj.ExpireIn || (!tokenObj.JwtToken)) {
      // 立即刷新token
      // config.baseURL="/api"
      if (!isRefreshing) {
        console.log('刷新token ing')
        isRefreshing = true
        refreshToken().then(res => {
          const { JwtToken, ExpireIn } = res;
          const tokenExpireTime = now + ExpireIn * 1000
          commonAxios.setToken({ 'JwtToken': JwtToken, 'ExpireIn': tokenExpireTime })
          isRefreshing = false
          return JwtToken
        }).then((JwtToken) => {
          console.log('刷新token成功，执行队列')
          requests.forEach(cb => cb(JwtToken))
          // 执行完成后，清空队列
          requests = []
        }).finally(data => {
          isRefreshing = false;
        }).catch(error => {
          console.log('refresh token error: ', error)
        })
      }
      const retryOriginalRequest = new Promise((resolve) => {
        requests.push((JwtToken) => {
          config.headers['Authorization'] = `Bearer ` + JwtToken
          resolve(config)
        })
      })
      return retryOriginalRequest
    }
  }


  //添加accesstoken
  if (window.location.origin.indexOf("localhost") >= 0) {
    config.headers.common['accesstoken'] = apiconfig['DEV_Token'];
  } else {
    if (!getCookie(apiconfig['enveriment']) || getCookie(apiconfig['enveriment']) == null) {
      let lid = qs.parse(window.location.href.split("?")[1])
      let calLID = lid[apiconfig['enveriment']] || lid[apiconfig['enveriment'].toLowerCase()];
      if (calLID) {
        Vue.$cookies.set(apiconfig['enveriment'], decodeURIComponent(calLID), 60 * 60 * 24, '/', '.cnki.net');
        // Vue.$cookies.set(apiconfig['enveriment'], decodeURIComponent(calLID), 60 * 60 * 24, '/', '192.168.50.179');
      } else {
        isLogin();
      }
    }
    config.headers.common['accesstoken'] = getCookie(apiconfig['enveriment']);

  }
  return config

}, (error) => {
  // Do something with request error
  return Promise.reject(error)
})


// 添加响应拦截器
commonAxios.interceptors.response.use(function (response) {
  let tokenObj = {};
  let obj = localStorage.getItem('token')
  tokenObj = obj ? JSON.parse(obj) : {}
  if (response.status == 200) {
    if (response.data.Code == -1 && response.config.url.indexOf("/ecptoken")) {
      isLogin();
    }
    if (response.data.errcode == 401 || response.data.Code == -1 || response.data.errcode == -1 || response.data.errcode == 40001 || response.data.Code == 5004 || response.data.Code == 5005) {
      // 立即刷新token
      if (tokenObj.JwtToken && tokenObj.ExpireIn || (!tokenObj.JwtToken)) {
        const now = Date.now()
        if (now >= tokenObj.ExpireIn || (!tokenObj.JwtToken)) {
          const config = response.config;
          // config.baseURL="/api";
          if (!isRefreshing) {
            isRefreshing = true
            const now = Date.now()
            window.localStorage.removeItem('token');

            refreshToken().then(res => {
              // debugger
              const { JwtToken, ExpireIn } = res;
              const tokenExpireTime = now + ExpireIn * 1000
              commonAxios.setToken({ 'JwtToken': JwtToken, 'ExpireIn': tokenExpireTime })
              config.headers['Authorization'] = `Bearer ` + JwtToken
              // config.baseURL = ''
              // 已经刷新了token，将所有队列中的请求进行重试
              requests.forEach(cb => cb(JwtToken))
              requests = []
              return commonAxios(config)
            }).finally(res => {
              isRefreshing = false;
            }).catch(res => {
              console.log('refreshtoken error =>', res)
              // window.location.href = '/'
            }).finally(() => {
              isRefreshing = false
            })

          }

          const retryOriginalRequest = new Promise((resolve) => {
            requests.push((JwtToken) => {
              response.headers['Authorization'] = `Bearer ` + JwtToken
              resolve(config)
            })
          })
          return retryOriginalRequest
        }
      }


    } else {


      // if (apiconfig.IS_MOCK) {
      //   //使用mock数据   
      //   let arr = response.config.url.split("/");
      //   let mocked = mockData[arr[arr.length - 1]]._mocked;
      //   response.data = tolower(mocked[`/${arr[arr.length-1]}${response.config.method}`].template());
      // } else {
      //   response.data = tolower(response.data);
      // }
      // return response.data;
    }
    return response.data;
  } else {
    switch (response.status) {
      case 400:
        console.log('错误请求')
        break
      case 401:
        console.log('未授权，请重新登录')
        isLogin()
        break
      case 403:
        console.log('拒绝访问')
        break
      case 404:
        console.log('请求错误,未找到该资源')
        break
      case 405:
        console.log('请求方法未允许')
        break
      case 408:
        console.log('请求超时')
        break
      case 500:
        console.log('服务器端出错')
        break
      case 501:
        console.log('网络未实现')
        break
      case 502:
        console.log('网络错误')
        break
      case 503:
        console.log('服务不可用')
        break
      case 504:
        console.log('网络超时')
        break
      case 505:
        console.log('http版本不支持该请求')
        break
      default:
        console.log(`连接错误${response.status}`)
    }
  }
}, function (error) {
  let tokenObj = {};
  let obj = localStorage.getItem('token')
  tokenObj = obj ? JSON.parse(obj) : {}
  if (error.response && error.response.status == 401) {
    if (tokenObj.JwtToken && tokenObj.ExpireIn || (!tokenObj.JwtToken)) {
      const now = Date.now()
      if (now >= tokenObj.ExpireIn || (!tokenObj.JwtToken)) {
        if (!isRefreshing) {
          isRefreshing = true
          const now = Date.now()
          window.localStorage.removeItem('token');
          const config = error.response.config;
          // config.baseURL="/api";
          refreshToken().then(res => {
            debugger
            const { JwtToken, ExpireIn } = res;
            const tokenExpireTime = now + ExpireIn * 1000
            commonAxios.setToken({ 'JwtToken': JwtToken, 'ExpireIn': tokenExpireTime })
            config.headers['Authorization'] = `Bearer ` + JwtToken
            // config.baseURL = ''
            // 已经刷新了token，将所有队列中的请求进行重试
            requests.forEach(cb => cb(JwtToken))
            requests = []
            return commonAxios(config)
          }).catch(res => {
            console.log('refreshtoken error =>', res)
            // window.location.href = '/'
          }).finally(() => {
            isRefreshing = false
          })

        } else {
          // // 正在刷新token，将返回一个未执行resolve的promise
          return new Promise((resolve) => {
            // 将resolve放进队列，用一个函数形式来保存，等token刷新后直接执行
            requests.push((token) => {
              // config.baseURL = ''
              config.headers['Authorization'] = `Bearer ` + token
              resolve(commonAxios(config))
            })
          })
        }

      }
    }

  }
  return Promise.reject(error);
});

function tolower(obj) {
  // 将所有返回的key转为小写
  for (let item in obj) {
    obj[item.toLocaleLowerCase()] = obj[item];
    if (Object.prototype.toString.call(obj[item]) == "[object Array]" || Object.prototype.toString.call(obj[item]) == "[object Object]") {
      obj[item] = tolower(obj[item]);
    }
  }
  return obj;
}



export default payAxios;